
package weaver.interfaces.ryKqzChange.action;

import com.engine.kq.biz.KQHolidaySetBiz;
import org.apache.commons.lang3.StringUtils;
import org.apache.tools.ant.util.DateUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *  新员工入职默认排班Action
 */
public class NewPersonSerialAction implements Action {

    private String sskqz;
    private String gzrbc;
    private String fgzrbc;
    private String rzrq;
    private String ryid;
    private String sfzh;

    static String dateFormat = "yyyy-MM-dd";
    static SimpleDateFormat format = new SimpleDateFormat(dateFormat);

    public NewPersonSerialAction() {
    }

    @Override
    public String execute(RequestInfo info) {
        BaseBean bb = new BaseBean();
        bb.writeLog("新员工入职默认排班");
        RecordSet rs = new RecordSet();
        try {
            //获取主表数据
            Map mainInfo = getMainInfo(info);
            //考勤组
            String kqz = Util.null2String(mainInfo.get(sskqz));
            //平时班次
            String bcId = Util.null2String(mainInfo.get(gzrbc));
            //周末班次
            String zmbc = Util.null2String(mainInfo.get(fgzrbc));
            //身份证号
            String zjhm = Util.null2String(mainInfo.get(sfzh));
            //入职日期
            String yprq = Util.null2String(mainInfo.get(rzrq));
            //人员id
            String userId = Util.null2String(mainInfo.get(ryid));

            String newPersonId = "-1";

            if(StringUtils.isNotBlank(zjhm)){
                newPersonId = findPersonId(zjhm);
            }

            if(StringUtils.isNotBlank(userId)){
                newPersonId = userId;
            }

            bb.writeLog("新入职员工id:"+newPersonId+" bcId:"+bcId+" zmbc:"+zmbc);
            //本年最后一天
            String toDateYear = yprq.substring(0,4)+"-12-31";
//            String toDate = TimeUtil.getMonthEndDay(yprq);
            Set<String> all = new HashSet<>();
            all.add(yprq);
            List<String> back = days(yprq,toDateYear);
            all.addAll(back);
            all.add(toDateYear);
            //插入考勤组
            insertGroupMember(rs,newPersonId,kqz,yprq,bb);
            bb.writeLog("考勤组插入完成");
            //默认排班
            String sql = "insert into kq_shiftschedule(kqdate,serialid,resourceid,groupid,isdelete)values(?,?,?,?,?)";
            for (String date : all) {
                boolean holiday = KQHolidaySetBiz.isHoliday(newPersonId, date, true);
                bb.writeLog("date:"+date+"holiday:"+holiday);
                if (holiday) {
                    //节假日休息班
                    if(StringUtils.isNotBlank(zmbc)){
                        rs.executeUpdate(sql, date, zmbc, newPersonId, kqz, "0");
                    }
                } else {
                    if(StringUtils.isNotBlank(bcId)){
                        rs.executeUpdate(sql, date, bcId, newPersonId, kqz, "0");
                    }
                }
            }
            bb.writeLog("默认排班插入完成");

        } catch (Exception e) {
            e.printStackTrace();
            bb.writeLog(e);
            bb.writeLog("新员工入职排班error"+e.getMessage());
            info.getRequestManager().setMessageid("2000");
            info.getRequestManager().setMessagecontent("新员工入职排班error");
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }

    /**
     * 找到新入职人员id
     * @param sfzh
     * @return
     */
    public static String findPersonId(String sfzh){
        String id = "0";
        RecordSet rs = new RecordSet();
        String sql = "select id from hrmresource where certificatenum = '"+sfzh+"' and status !=5";
        rs.executeQuery(sql);
        if (rs.next()){
            id = Util.null2String(rs.getString("id"));
        }
        return id;
    }


    /**
     * 获取两个日期之间所有的日期
     * @param date1
     * @param date2
     * @return
     */
    public static ArrayList days(String date1, String date2) {
        ArrayList L = new ArrayList();
        if (date1.equals(date2)) {
            System.out.println("两个日期相等!");
            return L;
        }

        String tmp;
        if (date1.compareTo(date2) > 0) { // 确保 date1的日期不晚于date2
            tmp = date1;
            date1 = date2;
            date2 = tmp;
        }

        tmp = format.format(str2Date(date1).getTime() + 3600 * 24 * 1000);

        int num = 0;
        while (tmp.compareTo(date2) < 0) {
            L.add(tmp);
            num++;
            tmp = format.format(str2Date(tmp).getTime() + 3600 * 24 * 1000);
        }

        if (num == 0)
            System.out.println("两个日期相邻!");
        return L;
    }

    private static Date str2Date(String str) {
        if (str == null)
            return null;

        try {
            return format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取主表数据
     *
     * @param requestInfo
     * @return
     */
    private static Map getMainInfo(RequestInfo requestInfo) {
        Map map = new HashMap();
        Property[] property = requestInfo.getMainTableInfo().getProperty();
        for (int i = 0; i < property.length; i++) {
            map.put(property[i].getName().toLowerCase(), Util.null2String(property[i].getValue()));
        }
        return map;
    }

    /**
     * 插入考勤组
     * @param rzry
     * @param groupId
     */
    private static void insertGroupMember(RecordSet rs,String rzry,String groupId,String validatefrom,BaseBean bb){
        String sql = "insert into kq_groupmember (type,typevalue,groupid,validatefrom,validateto) "
                + " values(?,?,?,?,?) ";
        rs.executeUpdate(sql, 1,rzry,groupId,validatefrom,"2999-12-31");
        bb.writeLog("insertSql:"+sql);
    }

}
